﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WebUpdateTool
{
    public partial class CongigSetting : Form
    {
        public CongigSetting()
        {
            InitializeComponent();
        }

        private void ConfigSetting_Load(object sender, EventArgs e)
        {
            var dirRules = GetAppConfigByString("app", "dirRules");
            var extensions = GetAppConfigByString("app", "Extensions");
            textBox1.Text = extensions.ToString();
            textBox2.Text = dirRules.ToString();
        }

        public static  string GetAppConfigByString(string ConfigName, string itemName)
        {
            string filePath = Application.StartupPath + "\\" + ConfigName + ".config";
            string content = File.ReadAllText(filePath, ASCIIEncoding.Unicode);
            var arrContent = content.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (arrContent.Length > 0)
            {
                foreach (var item in arrContent)
                {
                    var t = item.Split('=');
                    if (t[0] == itemName)
                    {
                        return t[1];
                    }
                } 
            } 
            return "";
        }

        private void UpdateAppConfig(string configContent)
        {
            string filePath = Application.StartupPath + "\\" + "app.config";
            if(textBox1.Text.Contains("=") || textBox1.Text.Contains("\\n"))
            {
                MessageBox.Show("请不要在文件过滤其中包含(=或\n等符号)");
                return;
            }
            if(textBox2.Text.Contains("=") || textBox2.Text.Contains("\\n"))
            {
                MessageBox.Show("请不要在文件夹过滤其中包含(=或\n等符号)");
                return;
            }
            if(!textBox1.Text.Contains("|"))
            {
               if( MessageBox.Show("您好，您当前对文件过滤器的设置将导致，过滤器失效，请参照例子","警告消息",MessageBoxButtons.OKCancel) !=DialogResult.OK)
               {
                   return;
               }
            }

            if (!textBox2.Text.Contains("|"))
            {
                if (MessageBox.Show("您好，您当前对文件夹过滤器的设置将导致，过滤器失效，请参照例子", "警告消息", MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    return;
                }
            }
            File.WriteAllText(filePath, configContent, Encoding.Unicode);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string content="Extensions="+textBox1.Text.Trim()+"\ndirRules="+textBox2.Text.Trim(); 
            UpdateAppConfig(content);
        }
    }
}
